package com.teaching.teachingsupport.common.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.teaching.teachingsupport.common.pojo.dto.request.UserLoginRequest;
import com.teaching.teachingsupport.common.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@RequiredArgsConstructor
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private final ObjectMapper objectMapper;
    private final SecurityUtils securityUtils;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("不支持的认证方法：" + request.getMethod());
        }

        if (request.getContentType() != null && request.getContentType().contains("application/json")) {
            try {
                // Read the request body
                String body = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
                UserLoginRequest loginRequest = objectMapper.readValue(body, UserLoginRequest.class);

                if (loginRequest.getUsername() == null) {
                    throw new AuthenticationServiceException("用户名不能为空");
                }
                if (loginRequest.getPassword() == null) {
                    throw new AuthenticationServiceException("密码不能为空");
                }

                String username = loginRequest.getUsername().trim();
                if (username.isEmpty()) {
                    throw new AuthenticationServiceException("用户名不能为空");
                }

                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, loginRequest.getPassword());
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (IOException e) {
                throw new AuthenticationServiceException("登录请求解析失败", e);
            }
        }

        // Fall back to form login if not JSON
        return super.attemptAuthentication(request, response);
    }
} 